package xdsclient

import "tmlake.com/api-gateway/istio-agent/xds/xdsclient/xdsresource"

func (c *clientImpl) MapRouteConfigs() map[string]xdsresource.RouteConfigUpdate {
	c.authorityMu.Lock()
	defer c.authorityMu.Unlock()

	maps := make([]map[string]xdsresource.RouteConfigUpdate, 0, len(c.authorities))
	for _, a := range c.authorities {
		maps = append(maps, a.MapRouteConfigs())
	}

	return mergeMapsRouteConfigs(maps)
}

func (c *clientImpl) MapEndpoints() map[string]xdsresource.EndpointsUpdate {
	c.authorityMu.Lock()
	defer c.authorityMu.Unlock()

	maps := make([]map[string]xdsresource.EndpointsUpdate, 0, len(c.authorities))
	for _, a := range c.authorities {
		maps = append(maps, a.MapEndpoints())
	}

	return mergeMapsEndpoints(maps)
}

func (c *clientImpl) MapClusters() map[string]xdsresource.ClusterUpdate {
	c.authorityMu.Lock()
	defer c.authorityMu.Unlock()

	maps := make([]map[string]xdsresource.ClusterUpdate, 0, len(c.authorities))
	for _, a := range c.authorities {
		maps = append(maps, a.MapClusters())
	}

	return mergeMapsClusters(maps)
}

func mergeMapsClusters(maps []map[string]xdsresource.ClusterUpdate) map[string]xdsresource.ClusterUpdate {
	ret := make(map[string]xdsresource.ClusterUpdate)
	for _, m := range maps {
		for k, v := range m {
			ret[k] = v
		}
	}

	return ret
}

func mergeMapsRouteConfigs(maps []map[string]xdsresource.RouteConfigUpdate) map[string]xdsresource.RouteConfigUpdate {
	ret := make(map[string]xdsresource.RouteConfigUpdate)
	for _, m := range maps {
		for k, v := range m {
			ret[k] = v
		}
	}

	return ret
}

func mergeMapsEndpoints(maps []map[string]xdsresource.EndpointsUpdate) map[string]xdsresource.EndpointsUpdate {
	ret := make(map[string]xdsresource.EndpointsUpdate)
	for _, m := range maps {
		for k, v := range m {
			ret[k] = v
		}
	}

	return ret
}
